package org.sang.controller.system;

import org.sang.bean.User;
import org.sang.bean.RespBean;
import org.sang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by sang on 2018/1/2.
 */
@RestController
@RequestMapping("/system/user")
public class SystemUserController {
    @Autowired
    UserService userService;

    @RequestMapping("/id/{userId}")
    public User getUserById(@PathVariable Long userId) {
        return userService.getUserById(userId);
    }

    @RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
    public RespBean deleteUser(@PathVariable Long userId) {
        if (userService.deleteUser(userId) == 1) {
            return new RespBean("success", "删除成功!");
        }
        return new RespBean("error", "删除失败!");
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    public RespBean updateUser(User user) {
        if (userService.updateUser(user) == 1) {
            return new RespBean("success", "更新成功!");
        }
        return new RespBean("error", "更新失败!");
    }

    @RequestMapping(value = "/roles", method = RequestMethod.PUT)
    public RespBean updateUserRoles(Long userId, Long[] rids) {
        if (userService.updateUserRoles(userId, rids) == rids.length) {
            return new RespBean("success", "更新成功!");
        }
        return new RespBean("error", "更新失败!");
    }

    @RequestMapping("/{keywords}")
    public List<User> getUsersByKeywords(@PathVariable(required = false) String keywords) {
        List<User> users = userService.getUsersByKeywords(keywords);
        return users;
    }


    @RequestMapping(value = "/user/reg", method = RequestMethod.POST)
    public ResponseEntity userReg(@RequestBody User user) {
        return ResponseEntity.ok(userService.add(user));
    }

}
